"""
智能路由系统示例
演示如何使用智能路由系统进行请求路由和模型选择
"""

import asyncio
import time
import json
from typing import Dict, Any

from middleware.smart_router import get_smart_router, init_smart_router
from utils.logger import Logger

logger = Logger.get_logger(agent_name="smart_router_example")


async def basic_routing_example():
    """
    基本路由示例：演示如何路由一个简单的文本问答请求
    """
    print("\n=== 基本路由示例 ===")
    
    # 获取智能路由实例
    router = await get_smart_router()
    
    # 简单的文本问答请求
    query = "什么是人工智能？请简要解释。"
    
    print(f"发送请求: {query}")
    result = await router.route_request(query)
    
    print(f"\n路由结果:")
    print(f"使用模型: {result['model']}")
    print(f"是否云端: {result['is_cloud']}")
    print(f"响应时间: {result['elapsed_time']:.2f}秒")
    print(f"是否成功: {result['success']}")
    print(f"\n路由决策理由:")
    for reason in result['decision_reasoning']:
        print(f"- {reason}")
    
    print(f"\n模型输出: {json.dumps(result['result'], ensure_ascii=False, indent=2)}")


async def custom_context_example():
    """
    自定义上下文示例：演示如何提供自定义请求上下文
    """
    print("\n=== 自定义上下文示例 ===")
    
    router = await get_smart_router()
    
    # 提供自定义上下文信息
    query = "请编写一个简单的Python函数，计算斐波那契数列"
    request_id = f"code_req_{int(time.time())}"
    user_id = "demo_user"
    
    print(f"发送带自定义上下文的请求: {query}")
    print(f"请求ID: {request_id}, 用户ID: {user_id}")
    
    result = await router.route_request(
        query,
        request_id=request_id,
        user_id=user_id,
        priority="high",  # 高优先级
        timeout=60.0,     # 60秒超时
        metadata={"project": "demo", "feature": "code_gen"}
    )
    
    print(f"\n路由结果:")
    print(f"请求ID: {result['request_id']}")
    print(f"使用模型: {result['model']}")
    print(f"响应时间: {result['elapsed_time']:.2f}秒")
    
    # 检查是否成功并显示结果
    if result['success']:
        print(f"\n代码生成成功！")
        code_result = result['result'].get('content', '').strip()
        print(f"生成的代码:\n{code_result}")
    else:
        print(f"生成失败: {result['result'].get('error', 'Unknown error')}")


async def multi_requests_example():
    """
    多请求并发示例：演示如何并发处理多个请求
    """
    print("\n=== 多请求并发示例 ===")
    
    router = await get_smart_router()
    
    # 准备多个不同类型的请求
    requests = [
        "解释量子计算的基本原理",
        "如何提高机器学习模型的准确率？",
        "请总结《三体》第一部的主要内容",
        "翻译'人工智能正在改变世界'为英文",
        "计算1987年7月1日到2023年12月31日之间有多少天"
    ]
    
    print(f"开始并发处理 {len(requests)} 个请求...")
    start_time = time.time()
    
    # 创建并发任务
    tasks = [router.route_request(query) for query in requests]
    results = await asyncio.gather(*tasks)
    
    elapsed = time.time() - start_time
    print(f"所有请求处理完成，总耗时: {elapsed:.2f}秒")
    print(f"平均响应时间: {elapsed/len(requests):.2f}秒/请求")
    
    # 显示每个请求的简要结果
    print("\n各请求简要结果:")
    for i, (query, result) in enumerate(zip(requests, results)):
        model = result['model']
        rt = result['elapsed_time']
        success = result['success']
        print(f"请求 {i+1}: {query[:40]}... -> 模型: {model}, 耗时: {rt:.2f}s, 成功: {success}")


async def request_type_detection_example():
    """
    请求类型检测示例：展示不同类型请求的路由行为
    """
    print("\n=== 请求类型检测示例 ===")
    
    router = await get_smart_router()
    
    # 不同类型的请求
    test_cases = [
        ("text_qa", "什么是机器学习中的过拟合问题？"),
        ("document_qa", "基于刚才提供的文档，总结主要观点"),
        ("code_generation", "请用JavaScript实现快速排序算法"),
        ("summarization", "请总结以下内容的关键点..."),
        ("multi_modal", "描述图片中的场景和人物"),
        ("tool_call", "搜索最新的Python版本及其特性")
    ]
    
    for expected_type, query in test_cases:
        # 分析请求
        context = router.analyze_request(query)
        
        print(f"\n查询: {query}")
        print(f"期望类型: {expected_type}")
        print(f"检测类型: {context.request_type}")
        print(f"所需能力: {context.required_capabilities}")
        
        # 路由请求
        result = await router.route_request(query)
        print(f"选择模型: {result['model']}")
        print(f"决策理由: {', '.join(result['decision_reasoning'][:2])}...")


async def performance_monitoring_example():
    """
    性能监控示例：展示如何监控和获取路由统计信息
    """
    print("\n=== 性能监控示例 ===")
    
    router = await get_smart_router()
    
    # 发送几个不同的请求以生成统计数据
    test_queries = [
        "什么是Python装饰器？",
        "解释什么是自然语言处理",
        "如何优化SQL查询性能？"
    ]
    
    print("发送测试请求以收集统计数据...")
    for query in test_queries:
        await router.route_request(query)
        await asyncio.sleep(1)  # 短暂延迟
    
    # 获取路由统计信息
    stats = router.get_routing_statistics()
    
    print("\n路由统计信息:")
    if not stats:
        print("暂无统计数据，请尝试发送更多请求")
    else:
        for model_request_type, metrics in stats.items():
            model, req_type = model_request_type.split(':', 1)
            total = metrics['total']
            success = metrics['success']
            failure = metrics['failure']
            timeout = metrics['timeout']
            
            success_rate = (success / total * 100) if total > 0 else 0
            print(f"\n模型: {model}, 请求类型: {req_type}")
            print(f"  总请求: {total}")
            print(f"  成功: {success} ({success_rate:.1f}%)")
            print(f"  失败: {failure}")
            print(f"  超时: {timeout}")


async def model_capabilities_example():
    """
    模型能力更新示例：演示如何更新模型能力信息
    """
    print("\n=== 模型能力更新示例 ===")
    
    router = await get_smart_router()
    
    # 更新一个模型的能力信息
    model_name = "custom_model"
    capabilities = ["coding", "math", "creative_writing", "translation"]
    
    print(f"更新模型 '{model_name}' 的能力信息:")
    print(f"新能力列表: {capabilities}")
    
    await router.update_model_capabilities(model_name, capabilities)
    
    # 验证更新是否生效（通过发送请求）
    query = "请写一首关于人工智能的诗"
    print(f"\n发送需要creative_writing能力的请求: {query}")
    
    try:
        result = await router.route_request(query)
        print(f"路由结果: 使用模型 {result['model']}")
        print(f"决策理由: {result['decision_reasoning']}")
    except Exception as e:
        print(f"处理请求时出错: {str(e)}")


async def handle_heavy_load_example():
    """
    高负载处理示例：演示系统在高负载下的路由行为
    """
    print("\n=== 高负载处理示例 ===")
    print("警告: 此示例将发送多个并发请求，可能会增加系统负载")
    
    # 询问是否继续
    proceed = input("是否继续? (y/N): ")
    if proceed.lower() != 'y':
        print("已取消高负载测试")
        return
    
    router = await get_smart_router()
    
    # 准备多个请求
    base_query = "请解释第{num}个自然数的数学性质"
    queries = [base_query.format(num=i) for i in range(1, 21)]  # 20个请求
    
    print(f"开始发送 {len(queries)} 个并发请求...")
    start_time = time.time()
    
    # 分批处理以避免过载
    batch_size = 5
    all_results = []
    
    for i in range(0, len(queries), batch_size):
        batch = queries[i:i+batch_size]
        print(f"\n处理批次 {i//batch_size + 1}/{(len(queries)+batch_size-1)//batch_size}")
        
        tasks = [router.route_request(q) for q in batch]
        batch_results = await asyncio.gather(*tasks, return_exceptions=True)
        all_results.extend(batch_results)
        
        # 短暂休息
        if i + batch_size < len(queries):
            await asyncio.sleep(2)
    
    elapsed = time.time() - start_time
    
    # 统计结果
    success_count = sum(1 for r in all_results if isinstance(r, dict) and r['success'])
    error_count = sum(1 for r in all_results if not isinstance(r, dict) or not r['success'])
    
    print(f"\n高负载测试完成")
    print(f"总耗时: {elapsed:.2f}秒")
    print(f"成功请求: {success_count}")
    print(f"失败请求: {error_count}")
    print(f"整体成功率: {(success_count / len(queries) * 100):.1f}%")


async def main():
    """
    主函数：运行所有示例
    """
    print("智能路由系统示例")
    print("=================")
    
    try:
        # 初始化智能路由系统
        print("\n正在初始化智能路由系统...")
        await init_smart_router()
        print("智能路由系统初始化完成")
        
        # 运行各个示例
        examples = [
            basic_routing_example,
            custom_context_example,
            multi_requests_example,
            request_type_detection_example,
            performance_monitoring_example,
            model_capabilities_example,
            handle_heavy_load_example
        ]
        
        # 交互式选择要运行的示例
        print("\n可用示例:")
        for i, example in enumerate(examples):
            print(f"{i+1}. {example.__name__.replace('_', ' ').title()}")
        print(f"0. 运行所有示例")
        
        choice = input("\n请选择要运行的示例 (0-7): ")
        
        try:
            choice = int(choice)
            if choice == 0:
                # 运行所有示例
                for example in examples:
                    await example()
                    print("\n" + "="*50)
                    await asyncio.sleep(1)
            elif 1 <= choice <= len(examples):
                # 运行选定的示例
                await examples[choice-1]()
            else:
                print("无效选择，运行基本示例")
                await basic_routing_example()
        except ValueError:
            print("输入错误，运行基本示例")
            await basic_routing_example()
            
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"\n运行示例时出错: {str(e)}")
    finally:
        print("\n示例程序结束")


if __name__ == "__main__":
    asyncio.run(main())
